<template>
    <ul class="list">
        <li class="item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        >{{item}}</li>
    </ul>
</template>

<script>
export default {
    name: 'CityAlphabet',
    props: {
        cities: [Object, Array]
    },
    computed: {
        letters () {
            const letters = []
            for (let i in this.cities) {
                letters.push(i)
            }
            return letters
        }
    },
    data () {
        return {
            touchStatus: false,
            startY: '',
            timer: null
        }
    },
    // 页面数据被更新并渲染完成之后执行的钩子
    updated () {
        // 提高性能  避免startY被多次重新计算
        this.startY = this.$refs['A'][0].offsetTop
    },
    methods: {
        handleLetterClick (e) {
            // 点击事件触发  则向父元素抛出 change事件 并传值
            this.$emit('change', e.target.innerText)
        },
        // 实现字母区手指滑动功能
        handleTouchStart () {
            this.touchStatus = true
        },
        handleTouchMove (e) {
            if (this.touchStatus) {
                // 实现函数节流 提高性能
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout(() => {
                    const touchY = e.touches[0].clientY - 79
                    // 20是每个字母的高度
                    const index = Math.floor((touchY - this.startY)) / 20
                    if (index >= 0 && index < this.letters.length) {
                        this.$emit('change', this.letters[index])
                    }
                }, 16)
            }
        },
        handleTouchEnd () {
            this.touchStatus = false
        }
    }
}
</script>

<style lang="stylus" scoped>
    @import '~styles/varibles.styl'
    .list
        z-index 3
        display flex
        flex-direction column
        justify-content center
        position absolute
        right .1rem
        top 1.58rem
        bottom 0
        width .4rem
        .item
            line-height .4rem
            text-align center
            color $bgColor
            font-size .3rem
</style>
